const { DataTypes } = require('sequelize')
const sequelize = require('../config/database')

const UserPermission = sequelize.define('UserPermission', {
  id: {
    type: DataTypes.INTEGER,
    primaryKey: true,
    autoIncrement: true,
    comment: '权限ID'
  },
  user_id: {
    type: DataTypes.INTEGER,
    allowNull: false,
    comment: '用户ID'
  },
  permissions: {
    type: DataTypes.JSON,
    allowNull: false,
    comment: '用户权限配置（JSON格式）'
  }
}, {
  tableName: 'user_permissions',
  timestamps: true,
  indexes: [
    {
      unique: true,
      fields: ['user_id']
    }
  ]
})

// 延迟设置关联关系，避免循环依赖
setTimeout(() => {
  const User = require('./user')

  UserPermission.belongsTo(User, {
    foreignKey: 'user_id',
    as: 'user'
  })
}, 0)

module.exports = UserPermission 